using System;
using UnityEngine.UIElements;
using static DA.AnimGraph.Editor.InspectorPane;

namespace DA.AnimGraph.Editor {

    internal class ShowInspectorService : Service {
        public void ShowInspector(InspectorDataSource source, Action saveCallback, ShowInspectorType showInspectorType) {
            (provider as InspectorPane).ShowInspector(source, saveCallback, showInspectorType);
        }
        public bool IsSourceEqual(InspectorDataSource source) {
            return (provider as InspectorPane).IsSourceEqual(source);
        }

        public void ClearInspector() {
            (provider as InspectorPane).ClearInspector();
        }
    }


    internal class InspectorPane : ContextPaneBase {

        public enum ShowInspectorType {
            New,
            Refresh,
        }

        InspectorDataSource source;
        PaneTitle paneTitle;
        VisualElement container;

        public InspectorPane(ContextPaneBase parent) : base(parent) {
            paneTitle = new PaneTitle("Inspector");
            Add(paneTitle);

            container = new ScrollView();
            container.style.flexGrow = 1;
            //container.StretchToParentSize();
            Add(container);
        }

        protected override void OnClearUI() {
            ageContext.serviceManager.RemoveService<ShowInspectorService>(this);
            ageEnv.OnModeChanged -= OnModeChanged;
            container.Clear();
            if (source != null) {
                source = null;
            }
        }

        protected override void OnDrawUI() {
            ageContext.serviceManager.AddService<ShowInspectorService>(this);
            ageEnv.OnModeChanged += OnModeChanged;
        }
        
        void OnModeChanged() {
            var newMode = ageEnv.ageMode;
            switch (newMode) {
                case AGEMode.Preview:
                    SetEnabled(false);
                    break;
                default:
                    SetEnabled(true);
                    break;
            }
        }

        internal void ShowInspector(InspectorDataSource source, Action saveCallback, ShowInspectorType showInspectorType) {
            if (source == null) {
                container.Clear();
                this.source = null;
                return;
            }
            if (this.source == source/* && showInspectorType == ShowInspectorType.New*/) {
                return;
            }
            container.Clear();
            this.source = source;
            source.DrawUI(container, ageContext, saveCallback);
        }
        internal bool IsSourceEqual(InspectorDataSource source) {
            return this.source == source;
        }

        internal void ClearInspector() {
            container.Clear();
        }
    }
}
